package cn.didi.feidi.androidorder.fragment.personal;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.donkingliang.labels.LabelsView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.OrderDetailActivity;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.OrderUser;
import cn.didi.feidi.androidorder.util.AppUtil;

public class PersonJudgeFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonAboutUsFragment";
    private LinearLayout personOrderDetail;
    private TextView personOrderId;
    private ImageView deliverIcon;
    private TextView deliverName;
    private TextView finishSendTime;
    private SimpleRatingBar deliveryJudge;
    private SimpleRatingBar goodsJudge;
    private LabelsView deliveryManJudgeLabels;
    private ArrayList<String> labels = new ArrayList<>();
    private CheckBox isNoNameJudge;
    private TextView isNoNameJudgeTv;
    private TextView commitjudge;

    private OrderUser orderUser;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonJudgeFragment newInstance(Bundle bundle) {
        PersonJudgeFragment fragment = new PersonJudgeFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderUser = (OrderUser) getActivity().getIntent().getSerializableExtra("orderUser");
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_judge, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }


    @Override
    protected void initViews(View rootView) {
        personOrderDetail = (LinearLayout) rootView.findViewById(R.id.person_judge_to_order_detail);
        personOrderId = (TextView) rootView.findViewById(R.id.person_judge_order_id);

        deliverIcon = (ImageView) rootView.findViewById(R.id.person_judge_deliver_icon);
        deliverName = (TextView) rootView.findViewById(R.id.person_judge_deliver_name);
        finishSendTime = (TextView) rootView.findViewById(R.id.person_judge_time);

        deliveryJudge = (SimpleRatingBar) rootView.findViewById(R.id.person_judge_delevery_judge);
        goodsJudge = (SimpleRatingBar) rootView.findViewById(R.id.person_judge_goods_judge);

        deliveryManJudgeLabels = (LabelsView) rootView.findViewById(R.id.person_judge_delevery_man_judge);

        isNoNameJudge = (CheckBox) rootView.findViewById(R.id.is_no_name_judge);
        isNoNameJudgeTv = (TextView) rootView.findViewById(R.id.person_judge_is_no_name_judge);
        commitjudge = (TextView) rootView.findViewById(R.id.person_judge_commit_judge);
    }

    @Override
    protected void initData() {
        personOrderId.setText(orderUser.getOrderUserId());
        deliverName.setText(orderUser.getWaterDeliverName());
        finishSendTime.setText(AppUtil.formatTimeInMillis(orderUser.getWaDeCoTi()));
        getCommentKeysInServer();
        getWaterDeliverIcon();
    }

    @Override
    protected void addListener() {
        isNoNameJudge.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isNoNameJudgeTv.setTextColor(Color.parseColor("#347cf1"));
                } else {
                    isNoNameJudgeTv.setTextColor(Color.parseColor("#999999"));
                }
            }
        });

        personOrderDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);

                intent.putExtra("orderUser", orderUser);
                startActivity(intent);

            }
        });

        commitjudge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitJudgeToServer();
            }
        });
    }

    private void getCommentKeysInServer() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());

        executeRequest(new AppActionRequest<>(Api.GET_COMMENT_KEYS, data, new TypeToken<ApiResponse<List<String>>>() {
        }.getType(), new ActionCallbackListener<List<String>>() {
            @Override
            public void onSuccess(String message, List<String> data) {
                labels = (ArrayList<String>) data;
                deliveryManJudgeLabels.setLabels(labels);
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
            }
        }));
    }

    private void commitJudgeToServer() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());
        data.put("orderUserId", orderUser.getOrderUserId());
        data.put("waterDeliverId", orderUser.getWaterDeliverId());
        data.put("content", getCommentResultLabels());
        data.put("deliverGrade", String.valueOf(deliveryJudge.getRating()));
        data.put("productGrade", String.valueOf(goodsJudge.getRating()));

        data.put("isAnonymous", isNoNameJudge.isChecked() + "");

        executeRequest(new AppActionRequest<>(Api.ADD_USER_COMMENT, data, new TypeToken<ApiResponse>() {
        }.getType(), new ActionCallbackListener<ApiResponse>() {
            @Override
            public void onSuccess(String message, ApiResponse data) {
                makeToast("评价成功");
                Intent intent = new Intent();
                intent.putExtra("refresh", true);
                getActivity().setResult(2, intent);
                getActivity().finish();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
            }
        }));
    }

    private String getCommentResultLabels() {
        Gson gson = new Gson();

        List<String> selectedLabers = new ArrayList<>();
        ArrayList<String> labelsString = deliveryManJudgeLabels.getLabels();
        for (Integer flag : deliveryManJudgeLabels.getSelectLabels()) {
            selectedLabers.add(labelsString.get(flag));
        }

        return gson.toJson(selectedLabers);
    }

    private void getWaterDeliverIcon() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());
        data.put("waterDeliverId", orderUser.getWaterDeliverId());

        executeRequest(new AppActionRequest<>(Api.GET_WATER_DELIVER_ICON_AND_PORTRAIT, data, new TypeToken<ApiResponse<String>>() {
        }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {

                Glide.with(mActivity).load(data).asBitmap().placeholder(R.drawable.person_center_person_default_icon).centerCrop().into(new BitmapImageViewTarget(deliverIcon) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        deliverIcon.setImageDrawable(circularBitmapDrawable);
                    }
                });

            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
            }
        }).setEmergency(true));
    }
}
